package com.frinder.http;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;

/**
 * @author frinder
 * @date 2018/10/22
 * @Description: ${todo}
 */
@Slf4j
public class HttpHelper {

    public static final HttpHelper HTTP_HELPER = new HttpHelper();

    /**
     * 保存properties属性
     */
    protected static final Map<String, String> PROPS = Maps.newConcurrentMap();

    /**
     * http client 对象
     */
    private final HttpClient client = HttpClients.createDefault();

    /**
     * 成功响应码
     */
    private final int ok = 200;

    /**
     * 登录标识
     */
    private boolean logged = false;

    private HttpHelper() {
    }

    /**
     * 初始化参数
     */
    static {
        try {
            Properties properties = new Properties();
            properties.load(HttpHelper.class.getResourceAsStream("/conf.properties"));
            Set<Map.Entry<Object, Object>> sets = properties.entrySet();
            for (Map.Entry<Object, Object> entry : sets) {
                PROPS.put(entry.getKey().toString(), entry.getValue().toString());
            }
            log.info("*** PROPS : {}", PROPS);
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        }
    }

    /**
     * 登录方法
     *
     * @throws Exception
     */
    public void login() throws Exception {
        if (!logged) {
            HttpResponse response = post(PROPS.get("sys.login"), PROPS);
            // 标识已登陆
            logged = (ok == response.getStatusLine().getStatusCode());
        }
    }

    /**
     * 登出方法
     *
     * @throws Exception
     */
    public void logout() throws Exception {
        if (logged) {
            try {
                post(PROPS.get("sys.logout"), null);
            } finally {
                logged = false;
            }
        }
    }

    /**
     * 处理 post请求
     *
     * @param url
     * @throws Exception
     */
    public HttpResponse post(String url, Map<String, String> params) throws Exception {
        log.info("***【POST】开始请求 : <<---------------------------------------------------------->>");
        // post 请求
        HttpPost post = new HttpPost(url);
        if (null != params && !params.isEmpty()) {
            // 登陆参数
            List<NameValuePair> formParams = Lists.newArrayList();
            for (Map.Entry<String, String> map : params.entrySet()) {
                formParams.add(new BasicNameValuePair(map.getKey(), map.getValue()));
            }
            if (!formParams.isEmpty()) {
                // 设置请求参数
                post.setEntity(new UrlEncodedFormEntity(formParams, "UTF-8"));
            }
        }
        log.info("***【POST】请求头: {}", JSON.toJSONString(post.getAllHeaders()));
        // 执行请求
        HttpResponse response = client.execute(post);
        log.info("***【POST】请求结束 : <<---------------------------------------------------------->>");
        return response;
    }

    /**
     * 处理 json post请求
     *
     * @param url
     * @throws Exception
     */
    public HttpResponse jsonPost(String url, String params) throws Exception {
        log.info("***【POST】开始请求 : <<---------------------------------------------------------->>");
        // post 请求
        HttpPost post = new HttpPost(url);
        StringEntity entity = new StringEntity(params, "UTF-8");
        entity.setContentEncoding("UTF-8");
        entity.setContentType("application/json");
        post.setEntity(entity);
        log.info("***【POST】请求头: {}", JSON.toJSONString(post.getAllHeaders()));
        // 执行请求
        HttpResponse response = client.execute(post);
        log.info("***【POST】请求结束 : <<---------------------------------------------------------->>");
        return response;
    }

    /**
     * 处理 get请求
     *
     * @param url
     * @throws Exception
     */
    public HttpResponse get(String url) throws Exception {
        log.info("***【GET】请求开始: <<---------------------------------------------------------->>");
        HttpGet get = new HttpGet(url);
        log.info("【GET】请求头: ", JSON.toJSONString(get.getAllHeaders()));
        // 执行请求
        HttpResponse response = client.execute(get);
        log.info("***【GET】请求结束: <<---------------------------------------------------------->>");
        return response;
    }

    /**
     * 打印结果
     *
     * @param response
     * @throws Exception
     */
    public void printResponse(HttpResponse response) throws Exception {
        log.info("***【开始打印】: <<---------------------------------------------------------->>");
        log.info("***【响应结果】: {}", response);
        if (response.getStatusLine().getStatusCode() == ok) {
            // 获取响应消息实体
            HttpEntity entity = response.getEntity();
            // 响应状态
            log.info("***【请求头】: {}", JSON.toJSONString(response.headerIterator()));
            // 判断响应实体是否为空
            if (entity != null) {
                String responseString = EntityUtils.toString(entity);
                log.info("***【响应内容】: {}", responseString);
            }
        } else {
            log.error("***请求失败！！！");
        }
        log.info("***【结束打印】: <<---------------------------------------------------------->>");
    }


}
